package com.atguigu.utils

import java.util.Properties

import io.searchbox.client.config.HttpClientConfig
import io.searchbox.client.{JestClient, JestClientFactory}
import io.searchbox.core.{Bulk, Index}

/**
 * Es连接工具
 *
 * @author WangJX
 * @date 2019/12/1 21:48 
 * @version 1.0
 */
object EsUtils {

  private var jestConn: JestClientFactory = null

  //创建Es连接实例
  def build: Unit = {
    val prop = new Properties()
    prop.load(EsUtils.getClass.getClassLoader.getResourceAsStream("es.properties"))
    val host: String = prop.getProperty("ES_HOST")
    val post: String = prop.getProperty("ES_HTTP_PORT")


    jestConn = new JestClientFactory
    //建立Es clinet的连接
    jestConn.setHttpClientConfig(new HttpClientConfig.Builder(host + ":" + post)
      .multiThreaded(true)
      .maxTotalConnection(20)
      .connTimeout(10000)
      .readTimeout(10000)
      .build())
  }


  def getConn = {
    if (jestConn == null) build
    jestConn.getObject
  }


  //关闭连接
  def close(conn: JestClient): Unit = {
    try {
      if (conn != null) {
        conn.shutdownClient()
      }
    }
    catch {
      case e: Exception => e.printStackTrace()
    }
  }


  /**
   * 批量推送数据到ES
   *
   * @param tableName
   * @param valueList
   */
  def insertBulk(tableName: String, valueList: List[(String, Any)]) = {

    val esConn: JestClient = getConn

    val builder: Bulk.Builder = new Bulk.Builder()

    for ((id, elem) <- valueList) {
      val indexBuilder = new Index.Builder(elem)
        .index(tableName)
        .`type`("_doc")
        .id(id)
        .build()

      //批量保存数据
      builder.addAction(indexBuilder)
    }

    //提交数据到Es  执行同步提交
    val items = esConn.execute(builder.build()).getItems

    if (items.size() > 0) {
      println("保存" + items.size() + "条数据到es中")
    }

    close(esConn)
  }



  def main(args: Array[String]): Unit = {

    val esConn: JestClient = getConn

/*    val index: Index = new Index.Builder(Stud(1, "zhangsan"))
      .index("gmall_stud")
      .`type`("_doc")
      .id("1")
      .build()*/

    val tuples: List[(String, Any)] = List[(String, Any)](("1", Stud(1, "zhangsan")),("2", Stud(2, "zhangsan2")),("3", Stud(3, "zhangsan3")))

    insertBulk("gmall_stud2", tuples)

    //单条插入一条数据到Es
//    esConn.execute(index)

    close(esConn)

    //    println(getConn)
  }

}

case class Stud(id: Int, name: String) {

}
